//
//  JYJVCOfSetContent.m
//  HappyListen
//
//  Created by 冀永金 on 16/9/3.
//  Copyright © 2016年 冀永金. All rights reserved.
//

#import "JYJVCOfSetContent.h"
#import "BaseTableView.h"
#import "Masonry.h"
#import "JYJVCOfRegister.h"
#import "JYJVCOfMine.h"
#import "JYJVCOfDiscover.h"
#import "JYJMusicMiniView.h"
#import "JYJVCOfAbout.h"
#import "BaseNavigationContoller.h"
@interface JYJVCOfSetContent ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) BaseTableView *tableView;
@end

@implementation JYJVCOfSetContent

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:0.09 green:0.09 blue:0.11 alpha:1.00];
    self.navigationItem.title = @"设置";
     self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    [self createTableView];
    [self createButton];
    // Do any additional setup after loading the view.
}
- (void)createButton {
    UIButton *backOfButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [backOfButton setTitle:@"退出登录" forState:UIControlStateNormal];
    [backOfButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    backOfButton.backgroundColor = [UIColor redColor];
    [self.view addSubview:backOfButton];
    [backOfButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view.mas_bottom).with.offset(0);
        make.left.equalTo(self.view.mas_left).with.offset(0);
        make.right.equalTo(self.view.mas_right).with.offset(0);
        make.height.mas_equalTo(50);
    }];
    [backOfButton addTarget:self action:@selector(handleBack:) forControlEvents:UIControlEventTouchUpInside];
    
}
- (void)createTableView {
    self.tableView = [[BaseTableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Set"];
    self.tableView.scrollEnabled = NO;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 2;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Set" forIndexPath:indexPath];
    NSArray *arr = @[@"清除缓存",@"关于"];
    cell.textLabel.text = arr[indexPath.row];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        [self createAlertController];
    }else {
        JYJVCOfAbout *about = [[JYJVCOfAbout alloc]init];
        self.tabBarController.tabBar.hidden = YES;
        self.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:about animated:YES];
    }
}

#pragma mark -  清除缓存功能实现
// 创建UIAlertController
- (void)createAlertController
{
    
    float cacheSize = [self currentCacheSize];
    
    //显示提示框.
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"缓存大小为%.2fM,确定要清理?", cacheSize] preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self ClearCache];
    }];
    [alertController addAction:actionCancel];
    [alertController addAction:actionOk];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

// 计算清除的缓存
- (float)currentCacheSize {
    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    return [self folderSizeAtPath:cachesPath];
}


// 遍历文件夹获得文件夹大小, 返回多少m
- (float) folderSizeAtPath:(NSString *)folderPath
{
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath])
    {
        return 0;
    }
    else
    {
        NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
        NSString *fileName;
        long long folderSize = 0;
        while ((fileName = [childFilesEnumerator nextObject]) != nil)
        {
            NSString *fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
            folderSize += [self fileSizeAtPath:fileAbsolutePath];
        }
        
        return folderSize / (1024.0 * 1024.0);
    }
}

// 计算单个文件的大小
- (long long)fileSizeAtPath:(NSString *)filePath
{
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]) {
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }else{
        return 0;
    }
}
// 清除缓存
- (void)ClearCache
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *path = [paths lastObject];
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:path];
    for (NSString *p in files)
    {
        NSError *error;
        NSString *Path = [path stringByAppendingPathComponent:p];
        if ([[NSFileManager defaultManager] fileExistsAtPath:Path])
        {
            [[NSFileManager defaultManager] removeItemAtPath:Path error:&error];
        }
    }
}
- (void)handleBack:(UIButton *)button {
    // 获取uersDeafaults的单例
    NSUserDefaults *usersDeafaults = [NSUserDefaults standardUserDefaults];
    // 根据key值移除用户名和密码
    [usersDeafaults removeObjectForKey:@"userName"];
    [usersDeafaults removeObjectForKey:@"passWord"];
    [usersDeafaults removeObjectForKey:@"info"];
    [usersDeafaults synchronize];
    JYJVCOfMine *vcOfMine = [[JYJVCOfMine alloc]init];
    [self.navigationController pushViewController:vcOfMine animated:YES];
    self.navigationController.viewControllers = @[vcOfMine];
        

}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [JYJMusicMiniView shareMiniView].hidden = YES;
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    //[JYJMusicMiniView shareMiniView].hidden = NO;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
